// 用户数据本地存储键
const USERS_STORAGE_KEY = 'simple_shop_users';
const CURRENT_USER_KEY = 'simple_shop_current_user';

// 获取存储的用户数据
function getUsers() {
    const users = localStorage.getItem(USERS_STORAGE_KEY);
    return users ? JSON.parse(users) : [];
}

// 保存用户数据
function saveUsers(users) {
    localStorage.setItem(USERS_STORAGE_KEY, JSON.stringify(users));
}

// 设置当前登录用户
function setCurrentUser(user) {
    const userData = { ...user };
    delete userData.password; // 不存储密码
    localStorage.setItem(CURRENT_USER_KEY, JSON.stringify(userData));
}

// 获取当前登录用户
function getCurrentUser() {
    const user = localStorage.getItem(CURRENT_USER_KEY);
    return user ? JSON.parse(user) : null;
}

// 退出登录
function logout() {
    localStorage.removeItem(CURRENT_USER_KEY);
    window.location.href = 'login.html';
}

// 检查用户是否已登录
function checkAuth() {
    const currentUser = getCurrentUser();
    const publicPages = ['login.html', 'register.html'];
    const currentPage = window.location.pathname.split('/').pop();

    if (!currentUser && !publicPages.includes(currentPage)) {
        // 未登录且不是公开页面，重定向到登录页
        window.location.href = 'login.html';
        return false;
    } else if (currentUser && publicPages.includes(currentPage)) {
        // 已登录但访问登录/注册页，重定向到首页
        window.location.href = 'index.html';
        return false;
    }
    return true;
}

// 处理注册表单提交
function handleRegister(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value.trim();
    const email = document.getElementById('email').value.trim();
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const errorElement = document.getElementById('registerError');
    
    // 显示错误信息
    function showError(message) {
        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }

    // 验证表单
    if (password !== confirmPassword) {
        showError('两次输入的密码不一致');
        return false;
    }

    if (password.length < 6) {
        showError('密码长度至少为6个字符');
        return false;
    }

    if (username.length < 3) {
        showError('用户名长度至少为3个字符');
        return false;
    }

    // 检查用户名是否已存在
    const users = getUsers();
    if (users.some(user => user.username === username)) {
        showError('用户名已被使用');
        return false;
    }

    // 检查邮箱是否已存在
    if (users.some(user => user.email === email)) {
        showError('邮箱已被注册');
        return false;
    }

    // 创建新用户
    const newUser = {
        username,
        email,
        password, // 实际应用中应该加密存储
        createdAt: new Date().toISOString()
    };

    // 保存用户数据
    users.push(newUser);
    saveUsers(users);

    // 自动登录
    setCurrentUser(newUser);

    // 跳转到首页
    window.location.href = 'index.html';
    return false;
}

// 处理登录表单提交
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    const errorElement = document.getElementById('loginError');
    
    // 显示错误信息
    function showError(message) {
        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }

    // 验证用户
    const users = getUsers();
    const user = users.find(u => u.username === username && u.password === password);

    if (!user) {
        showError('用户名或密码错误');
        return false;
    }

    // 设置当前用户
    setCurrentUser(user);

    // 跳转到首页
    window.location.href = 'index.html';
    return false;
}

// 更新页面头部显示用户信息
function updateUserInfo() {
    const currentUser = getCurrentUser();
    const headerElement = document.querySelector('header');
    
    if (currentUser && headerElement) {
        // 检查是否已经添加了用户信息
        if (!document.getElementById('userInfo')) {
            const userInfo = document.createElement('div');
            userInfo.id = 'userInfo';
            userInfo.style.cssText = `
                position: absolute;
                right: 1rem;
                top: 50%;
                transform: translateY(-50%);
                display: flex;
                align-items: center;
                gap: 1rem;
            `;
            
            userInfo.innerHTML = `
                <span>欢迎，${currentUser.username}</span>
                <button onclick="logout()" style="
                    background: #e74c3c;
                    color: white;
                    border: none;
                    padding: 0.5rem 1rem;
                    border-radius: 4px;
                    cursor: pointer;
                ">退出登录</button>
            `;
            
            headerElement.style.position = 'relative';
            headerElement.appendChild(userInfo);
        }
    }
}

// 页面加载时检查认证状态
document.addEventListener('DOMContentLoaded', () => {
    if (checkAuth()) {
        updateUserInfo();
    }
});